package com.cqupt.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;

/**
 * 日期工具类
 * 将时间戳转为可读日期
 *
 * @author Tyc
 **/
public class DateUtils {

    private final static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 格式化List里的"r_clock"键对应的时间
     *
     * @param dataMap 要格式化的Map
     */
    public static void formatListRecoveryClock(Map<String, Object> dataMap) {
        String clock = "尚未恢复";
        String r_clock = (String) dataMap.get("r_clock");
        if (!r_clock.equals("0")) {
            // 表明有已记录的时间戳
            clock = sdf.format(new Date(Long.parseLong(r_clock) * 1000L));
        }
        dataMap.put("r_clock", clock);
    }

    /**
     * @param dataMap 要格式化的map
     * @param key     要格式化的key值
     */
    public static void formatListDate(Map<String, Object> dataMap, String key) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        String temp = dataMap.get(key).toString();

        if (Pattern.matches("^[0-9]+$", temp)) {
            // 合法输入
            Date date = new Date(Long.parseLong(temp) * 1000L);

            simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT+8"));//时区设置
            String clock = simpleDateFormat.format(date);

            dataMap.put(key, clock);
        }
    }

    /**
     * 转换为时间戳，单位秒
     *
     * @param dateStr 要转换的时间字符串
     * @return 时间戳Long
     */
    public static Long toTimeStamp(String dateStr) {
        String formatString1 = "EEE MMM dd yyyy HH:mm:ss z";
        String[] replaceString = new String[]{"GMT+0800", "GMT+08:00"};
        String splitString = " (中国标准时间)";

        dateStr = dateStr.split(Pattern.quote(splitString))[0].replace(replaceString[0], replaceString[1]);
        SimpleDateFormat sdf1 = new SimpleDateFormat(formatString1, Locale.ENGLISH);
        Long res = null;
        try {
            Date date = sdf1.parse(dateStr);
            // API的Timestamp是秒，getTime()是毫秒，需要/1000
            res = date.getTime() / 1000;
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return res;
    }

    /**
     * @description: 截取指定时间范围数据
     */
    public static List<Map<String, Object>> getSpecifiedTimeData(List<Map<String, Object>> dataList, String startDate, String endDate) {
        List<Map<String, Object>> returnList = new ArrayList<>();

        try {
            Date startTime = sdf.parse(startDate + " 00:00:00");
            Date endTime = sdf.parse(endDate + " 23:59:59");
            Calendar start = Calendar.getInstance();
            Calendar end = Calendar.getInstance();

            start.setTime(startTime);
            end.setTime(endTime);

            for (int i = 0; i < dataList.size(); i++) {
                Calendar date = Calendar.getInstance();
                Date nowDate = sdf.parse(dataList.get(i).get("clock").toString());
                date.setTime(nowDate);

                if (date.after(start) || start == date) {//确定截取的开始时间
                    for (int j = i; j < dataList.size() - i; j++) {
                        Date newNowDate = sdf.parse(dataList.get(j).get("clock").toString());
                        date.setTime(newNowDate);
                        if (date.after(end)) {//确定截取的终止时间
                            break;
                        }
                        returnList.add(dataList.get(j));
                    }
                    break;
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return returnList;
    }


    /**
     * @description: 截取指定时间范围数据
     */
    public static List<Map<String, Object>> getSpecifiedTimeDataDesc(List<Map<String, Object>> dataList, String startDate, String endDate) {
        int startnum = -1, endnum = -1;
        try {
            if (startDate.equals("") || endDate.equals("")){
                return dataList;
            }else{
                Date startTime = sdf.parse(startDate + " 00:00:00");
                Date endTime = sdf.parse(endDate + " 23:59:59");
                Calendar start = Calendar.getInstance();
                Calendar end = Calendar.getInstance();

                start.setTime(startTime);
                end.setTime(endTime);


                for (int i = 0; i < dataList.size(); i++) {
                    Calendar date = Calendar.getInstance();
                    Date nowDate = sdf.parse(dataList.get(i).get("clock").toString());
                    date.setTime(nowDate);
                    if (date.before(end)){
                        startnum = i;
                        break;
                    }
                }
                for (int i = dataList.size() - 1; i >= 0 ; i--) {
                    Calendar date = Calendar.getInstance();
                    Date nowDate = sdf.parse(dataList.get(i).get("clock").toString());
                    date.setTime(nowDate);
                    if (date.after(start)){
                        endnum = i;
                        break;
                    }
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return dataList.subList(startnum, endnum + 1);
    }

    /**
     * @param dataMap 要格式化的map
     * @param key     要格式化的key值
     */
    public static void formatRunDate(Map<String, Object> dataMap, String key) {
//        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        String mss = dataMap.get(key).toString();
        long num = Long.parseLong(mss);
        String DateTimes = null;
        long days = num / (60 * 60 * 24);
        long hours = (num % (60 * 60 * 24)) / (60 * 60);
        long minutes = (num % (60 * 60)) / 60;
        long seconds = num % 60;
        if (days > 0) {
            DateTimes = days + "天" + hours + "小时" + minutes + "分钟"
                    + seconds + "秒";
        } else if (hours > 0) {
            DateTimes = hours + "小时" + minutes + "分钟"
                    + seconds + "秒";
        } else if (minutes > 0) {
            DateTimes = minutes + "分钟"
                    + seconds + "秒";
        } else {
            DateTimes = seconds + "秒";
        }
        dataMap.put(key, DateTimes);
//        if (Pattern.matches("^[0-9]+$", temp)){
//            // 合法输入
//            Date date = new Date(Long.parseLong(temp) * 1000L);
//
//            simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT+8"));//时区设置
//            String clock = simpleDateFormat.format(date);
//
//            dataMap.put(key, clock);
//        }
    }

    public static Map<String, Object> JsonToMap(JSONObject obj) {
        Map<String, Object> data = new HashMap<>();
        //循环转换
        Iterator it = obj.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, Object> entry = (Map.Entry<String, Object>) it.next();
            data.put(entry.getKey(), entry.getValue());
        }
        return data;
    }

    /**
     * @param DateStr 要格式化的时间戳 （秒级别）
     * @return 返回格式化后的日期（年月日时分秒）
     */
    public static String SecondTimeStamp2Date(String DateStr) {
        Long clock = Long.valueOf(DateStr + "000");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String sd = sdf.format(new Date(Long.parseLong(String.valueOf(clock))));
        return sd;
    }

    /**
     * @param DateStr 要格式化的时间戳 （毫秒秒级别）
     * @return 返回格式化后的日期（年月日时分秒）
     */
    public static String MilliSecondTimeStamp2Date(String DateStr) {
        Long clock = Long.valueOf(DateStr);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String sd = sdf.format(new Date(Long.parseLong(String.valueOf(clock))));
        return sd;
    }


    /**
     *  日期转时间戳 （毫秒级别，需要/1000转为秒级别）
     * @param timers
     * @return
     */

    public static long timeToStamp(String timers) {
        Date d = new Date();
        long timeStemp = 0;
        try {
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            d = sf.parse(timers);// 日期转换为时间戳
        } catch (ParseException e) {
            e.printStackTrace();
        }
        timeStemp = d.getTime();
        return timeStemp;
    }

    /**
     * 日期转星期（eg. 2021-08-18 21:48:12  --> 星期三）
     * @param datetime
     * @return
     */
    public static String dateToWeek(String datetime) {
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String[] weekDays = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
        Calendar cal = Calendar.getInstance();
        Date datet = null;
        try {
            datet = f.parse(datetime);
            cal.setTime(datet);
        } catch (ParseException e) {
            e.getMessage();
        }
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0)
            w = 0;
        return weekDays[w];
    }

    // 比较俩数组中的相同元素
    public static float getAllSameElement(String[] strArr1,String[] strArr2) {
        if(strArr1 == null || strArr2 == null) {
            return -1;
        }
        List<String> strList1 = new ArrayList<String>(Arrays.asList(strArr1));
        List<String>  strList2 = new ArrayList<String>(Arrays.asList(strArr2));

        strList1.retainAll(strList2);
        return strList1.size();
    }

    /**
     * object对象转map
     * @param object
     * @return
     * @throws IllegalAccessException
     */
    public static Map<String, Object> objectToMap(Object object) {
        if (object == null) {
            return null;
        }
        return JSON.parseObject(JSON.toJSONString(object), Map.class);
    }

}
